package cn.getech.data.development.service.impl;

import cn.getech.data.development.constant.PermissionTypeEnum;
import cn.getech.data.development.constant.StoreTableType;
import cn.getech.data.development.entity.TableFieldInfo;
import cn.getech.data.development.entity.TableFieldRules;
import cn.getech.data.development.mapper.TableFieldInfoMapper;
import cn.getech.data.development.mapper.TableFieldRulesMapper;
import cn.getech.data.development.service.RangerDataService;
import cn.getech.data.development.service.TableFieldInfoService;
import cn.getech.data.development.service.TableInfoService;
import cn.getech.data.development.utils.DataPermissionUtil;
import cn.getech.system.center.entity.RoleRowDataPermissionConfig;
import cn.getech.system.center.mapper.RoleRowDataPermissionConfigMapper;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 表字段信息 服务实现类
 * </p>
 *
 * @author zenith
 * @since 2019-07-08
 */
@Slf4j
@Service
public class TableFieldInfoServiceImpl extends ServiceImpl<TableFieldInfoMapper, TableFieldInfo> implements TableFieldInfoService {

    @Autowired
    private TableFieldInfoMapper tableFieldInfoMapper;

    @Autowired
    private TableFieldRulesMapper tableFieldRulesMapper;

    @Autowired
    private RoleRowDataPermissionConfigMapper roleRowDataPermissionConfigMapper;

    @Autowired
    private RangerDataService rangerDataService;

    @Autowired
    private TableInfoService tableInfoService;

    @Override
    public void deleteByTableFieldIds(List<Integer> needDelTableFieldIds) {
        for (Integer needDelTableFieldId : needDelTableFieldIds) {
            tableFieldInfoMapper.deleteById(needDelTableFieldId);
            try {
                List<TableFieldRules> tableFieldRules = tableFieldRulesMapper.selectList(new QueryWrapper<TableFieldRules>().eq("table_field_id", needDelTableFieldId));
                if (CollectionUtil.isNotEmpty(tableFieldRules)) {
                    for (TableFieldRules tableFieldRule : tableFieldRules) {
                        tableFieldRulesMapper.deleteById(tableFieldRule.getId());
                        roleRowDataPermissionConfigMapper.delete(new QueryWrapper<RoleRowDataPermissionConfig>().eq("table_field_rules_id", tableFieldRule.getId()));
                    }
                }
            } catch (Exception e) {
                log.error("删除表字段行规则异常，error:{}", e.getMessage());
            }
            try {
                rangerDataService.deleteRangerPolicyMasking(needDelTableFieldId);
            } catch (Exception e) {
                log.error("删除表字段脱敏规则异常，error:{}", e.getMessage());
            }
        }
    }

    @Override
    public IPage<TableFieldInfo> page(IPage<TableFieldInfo> page, Integer id) {
        Long userId = ShiroUtils.getUserId();
        QueryWrapper<TableFieldInfo> wrapper = new QueryWrapper<>();
        if (!tableInfoService.checkPermission(id)) {
                //先判断申请权限
                List<Integer> applyDataIds = DataPermissionUtil.getApplyDataIds(userId, PermissionTypeEnum.QUERY.getType());
                if (!applyDataIds.contains(id)) {
                    //判断数据权限
                    List<Integer> ids = DataPermissionUtil.getDataIds(
                            userId.intValue(), PermissionTypeEnum.STORE_FILED.getType(), PermissionTypeEnum.QUERY.getType());
                    //申请的字段权限id
                     ids.addAll(DataPermissionUtil.getCreateFiledIds(id,userId,StoreTableType.OFFLINE.getCode()));

                    if (CollectionUtils.isNotEmpty(ids)) {
                        wrapper.and(w -> w.in("id", ids).or().eq("create_per", userId)
                        );
                    } else {
                        wrapper.and(w -> w.eq("create_per", userId)
                        );
                    }
                }
        }
        wrapper.eq("table_id", id);
        wrapper.orderByAsc("field_order", "is_partition");
        return baseMapper.selectPage(page, wrapper);
    }

    @Override
    public List<TableFieldInfo> list(QueryWrapper<TableFieldInfo> wrapper, Integer id) {
        wrapper.eq("table_id", id);
        wrapper.orderByAsc("field_order","is_partition");
        if (!tableInfoService.checkPermission(id)) {
            Long userId = ShiroUtils.getUserId();
            if (!DataPermissionUtil.isAdmin(userId.intValue())) {
                //先判断申请权限
                List<Integer> applyDataIds = DataPermissionUtil.getApplyDataIds(userId, PermissionTypeEnum.QUERY.getType());
                if (!applyDataIds.contains(id)) {
                    //判断数据权限
                    List<Integer> ids = DataPermissionUtil.getDataIds(
                            userId.intValue(), PermissionTypeEnum.STORE_FILED.getType(), PermissionTypeEnum.QUERY.getType());
                    //申请的字段权限id
                    ids.addAll(DataPermissionUtil.getCreateFiledIds(id,userId, StoreTableType.OFFLINE.getCode()));

                    if (CollectionUtils.isEmpty(ids)) {
                        wrapper.and(w -> w.eq("create_per", userId));
                    } else {
                        wrapper.and(w -> w.in("id", ids).or().eq("create_per", userId)
                        );
                    }
                }

            }
        }
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<TableFieldInfo> getFileds(QueryWrapper<TableFieldInfo> wrapper, Integer tableId, Integer filedType) {
        wrapper.eq("table_id", tableId);
        wrapper.orderByAsc("field_order","is_partition");
        String[] fieldTypeArr;
        if(filedType == 1){//文本型
            fieldTypeArr = new String[]{"STRING", "VARCHAR", "CHAR"};
        }else if (filedType == 2){//数值型
            fieldTypeArr = new String[]{"TINYINT", "SMALLINT", "INT", "BIGINT", "FLOAT", "DOUBLE", "DECIMAL"};
        }else if (filedType == 4){//枚举型
            fieldTypeArr = new String[]{"MAP","STRUCT"};
        }else{//日期型
            fieldTypeArr = new String[]{"TIMESTAMP", "DATE", "INTERVAL", "DATETIME"};
        }
        if (filedType == 4){
            wrapper.like("field_type", "MAP").or().like("field_type", "STRUCT");
        }else {
            wrapper.in("field_type",fieldTypeArr);
        }

        if (!tableInfoService.checkPermission(tableId)) {
            Long userId = ShiroUtils.getUserId();
            if (!DataPermissionUtil.isAdmin(userId.intValue())) {
                //先判断申请权限
                List<Integer> applyDataIds = DataPermissionUtil.getApplyDataIds(userId, PermissionTypeEnum.QUERY.getType());
                if (!applyDataIds.contains(tableId)) {
                    //判断数据权限
                    List<Integer> ids = DataPermissionUtil.getDataIds(
                            userId.intValue(), PermissionTypeEnum.STORE_FILED.getType(), PermissionTypeEnum.QUERY.getType());
                    //申请的字段权限id
                    ids.addAll(DataPermissionUtil.getCreateFiledIds(tableId,userId, StoreTableType.OFFLINE.getCode()));

                    if (CollectionUtils.isEmpty(ids)) {
                        wrapper.and(w -> w.eq("create_per", userId));
                    } else {
                        wrapper.and(w -> w.in("id", ids).or().eq("create_per", userId)
                        );
                    }
                }

            }
        }

        return baseMapper.selectList(wrapper);
    }
}
